package com.zpp.common.security.service;

import cn.hutool.core.lang.UUID;
import com.zpp.common.core.constants.CacheConstants;
import com.zpp.common.core.constants.JwtConstants;
import com.zpp.common.core.enums.UserIdentity;
import com.zpp.common.redis.service.RedisService;
import com.zpp.common.core.domain.LoginUser;
import com.zpp.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {
    @Autowired
    private RedisService redisService;

    //生成token
    public String createToken(long userId, String secret, UserIdentity userIdentity, String nickName, String headImage) {
        //生成UUID作为每位用户是唯一标识
        String userKey = UUID.fastUUID().toString();

        //map对象存放userId信息和uuid
        Map<String, Object> map = new HashMap<>();
        map.put(JwtConstants.LOGIN_USER_ID,userId);
        map.put(JwtConstants.LOGIN_USER_KEY, userKey);
        //生成token
        String token = JwtUtils.createToken(map, secret);

        //生成redis的key
        String key  = getKey(userKey);
        //生成redis的value
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(userIdentity.getValue());
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        //往redis中存储信息
        redisService.setCacheObject(key, loginUser, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);

        //返回token
        return token;
    }

    //延长token
    public void extendToken(Claims claims) {
        String userKey = getUserKey(claims); //通过token,获取userKey(唯一标识UUID)
        if(userKey == null) {
            return;
        }

        String key  = CacheConstants.LOGIN_TOKEN_KEY + userKey;

        //设置redis的过期时间
        Long ttl = redisService.getExpire(key, TimeUnit.MINUTES);  //获取过期时间
        if(ttl != null && ttl < CacheConstants.REFRESH_TIME) {
            redisService.expire(key, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        }
    }

    public boolean deleteToken(String token, String secret) {
        //解析token，获取token中的userKey(唯一标识UUID)
        String userKey = getUserKey(token, secret);
        if(userKey == null){
            return false;
        }
        String key  = getKey(userKey);
        return redisService.deleteObject(key);
    }

    public LoginUser getInfo(String token, String secret) {
        //解析token，获取token中的userKey(唯一标识UUID)
        String userKey = getUserKey(token, secret);
        if(userKey == null){
            return null;
        }
        String key  = getKey(userKey);

        return  redisService.getCacheObject(key, LoginUser.class);
    }


    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return  Long.valueOf(JwtUtils.getUserId(claims)); //获取jwt中的key
    }


    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        String userKey = JwtUtils.getUserKey(claims); //获取jwt中的key
        return userKey;
    }

    public String getUserKey(String token,String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        String userKey = JwtUtils.getUserKey(claims); //获取jwt中的key
        return userKey;
    }


    //生成redis的key
    public String getKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret);  //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("token：{}解析出现异常", token);
                return null;
            }
        } catch (Exception e) { //如果令牌被修改无法正确解析则会抛出异常
            log.error("token：{}解析出现异常", token,e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String key  = getKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(key, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);

        redisService.setCacheObject(key, loginUser);
    }

}
